﻿using System;
using System.Collections.Generic;

namespace Vbyte.DataSource.Cache
{

    /// <summary>
    /// 通用数据类型缓存（内存缓存）
    /// </summary>
    /// <typeparam name="TData">缓存的数据类型</typeparam>
    public class GenericCache<TData>
    {
        private static Dictionary<string, TData> CacheDict = new Dictionary<string, TData>(StringComparer.Ordinal);

        /// <summary>
        /// 获取指定键值的数据
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="fetchMethod">不存在该键值数据时获取数据的相关方法</param>
        /// <returns>特定键值类型的缓存数据</returns>
        public static TData Get(string key, Func<TData> fetchMethod)
        {
            if (!CacheDict.ContainsKey(key))
            {
                CacheDict.Add(key, fetchMethod());
            }
            return CacheDict[key];
        }
		
		
		/// <summary>
        /// 设置指定键值的数据
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="dat">相关键值数据</param>
        public static void Set(string key, TData dat)
        {
            if (!CacheDict.ContainsKey(key))
            {
                CacheDict.Add(key, dat);
            }
            else
            {
                CacheDict[key] = dat;
            }
        }
    }
}
